package echo.demo2.codec;

import com.fasterxml.jackson.databind.ObjectMapper;
import echo.protocol.MessageProtocol;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class Demo2Decoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < 4) {
            return;
        }
        in.markReaderIndex();
        int dataLength = in.readInt();
        if (in.readableBytes() < dataLength) {
            in.resetReaderIndex();
            return;
        }
        byte[] data = new byte[dataLength];
        ObjectMapper ob = new ObjectMapper();
        in.readBytes(data);
        MessageProtocol messageProtocol = ob.readValue(data, MessageProtocol.class);
        out.add(messageProtocol);
    }
}
